Ext.define('hkyg.view.NewsPanel',{
	extend: 'Ext.container.Viewport',
	alias: 'widget.newsPanel',
	requires:[
		'hkyg.view.EdtUserInfo',
		'hkyg.view.FileUploadForm'
	],
	layout: 'accordion',
	initComponent: function() {
		var me = this;
		me.newsStore = Ext.create('hkyg.store.WebContent',{pageSize: 25});
		me.usersStore = Ext.create('hkyg.store.UserInfo',{pageSize: 25});
		Ext.apply(Ext.form.VTypes, {
		     repetition: function(val, field) {     //返回true，则验证通过，否则验证失败
		         if (field.repetition) {               //如果表单有使用repetition配置，repetition配置是一个JSON对象，该对象提供了一个名为targetCmpId的字段，该字段指定了需要进行比较的另一个组件ID。
		             var cmp = Ext.getCmp(field.repetition.targetCmpId);   //通过targetCmpId的字段查找组件
		             if (Ext.isEmpty(cmp)) {      //如果组件（表单）不存在，提示错误
		                 Ext.MessageBox.show({
		                     title: '错误',
		                     msg: '发生异常错误，指定的组件未找到',
		                     icon: Ext.Msg.ERROR,
		                     buttons: Ext.Msg.OK
		                 });
		                 return false;
		             }
		             if (val == cmp.getValue()) {  //取得目标组件（表单）的值，与宿主表单的值进行比较。
		                 return true;
		             } else {
		                 return false;
		             }
		         }
		     },
		     repetitionText: '两次密码输入不一致'
	    });
		me.items = [{
			xtype: 'panel',
			title: '新闻维护',
			border: 0,
			iconCls: 'hkyg-news',
			layout: 'border',
			items: [{
				xtype: 'grid',
				store: me.newsStore,
				border: 0,
				split: true,
				collapsible: true,
				collaseDirection: 'left',
				region: 'west',
				flex: 1,
				itemId: 'newsGrid',
				columns: [{
					text: '标题',
					dataIndex: 'title',
					flex: 1
				},{
					text: '创建者',
					dataIndex: 'create_user',
					flex: 1
				},{
					xtype:'datecolumn',
					dataIndex:'create_time',
					format:'m-d H:i:s',
					flex: 1,
					text: '创建时间'
				},{
					text: '最后修改人',
					dataIndex: 'modify_user',
					flex: 1
				},{
					xtype:'datecolumn',
					dataIndex:'modify_time',
					format:'m-d H:i:s',
					flex: 1,
					text: '更新时间'
				}],
				tbar: [{
					text: '新增',
					iconCls: 'hkyg-news-add',
					itemId: 'addNews'
				},{
					text: '删除',
					iconCls: 'hkyg-news-del',
					itemId: 'delNews'
				},'-',{
					xtype: 'textfield',
					itemId: 'searchTitle',
					emptyText: '标题',
					enableKeyEvents: true,
		 	 		listeners: {
			 	 		keypress: function(scope, e) {
							if(e.keyCode == e.ENTER || e.keyCode == 10) {
								me.doSearch();
							}
			 	 		}
		 	 		}
				},{
					text: '搜索',
					itemId: 'searchBtn',
					iconCls: 'hkyg-search'
				}],
				dockedItems: [{
		            xtype: 'pagingtoolbar',
		            store: me.newsStore,   // same store GridPanel is using
		            dock: 'bottom',
		            displayInfo: true
		        }]
			},{
				xtype: 'panel',
				region: 'center',
				itemId: 'contentPanel',
				layout: 'border',
				border: 0,
				flex: 1,
				items: [{
					xtype: 'textfield',
					fieldLabel: '标题',
					itemId: 'title',
					region: 'north',
					labelAlign: 'right',
					margin: '10 10 10 10'
				},{
					xtype: 'htmleditor',
					itemId: 'content',
					region: 'center',
					flex: 1,
					margin: '10 10 10 10'
				}],
				buttons: [{
					xtype: 'fileUploadX',
					height: 22,
					onlyImg: true,
					border: 0,
					disabled: false,
					extraParams: {pg_type: "图片"},
					itemId: 'insertImage',
					fileFieldConfig: {
						buttonOnly: true,
						buttonConfig: {
							text: '插入图片',
							iconCls: 'hkyg-pic'								
						}
					},
					listeners: {
						afterSave: function(scope, result){
							//新增数据仓库记录（这个form已经帮我们完成）
							if(result.success) {
								  var pg_id = result.pg_id;
							      var src = 'hkyg/downloadFile.do?pg_id=' + pg_id;
							      me.down('htmleditor').insertAtCursor('<img src=\'' + src + '\'/>');
							}		
						}
					}
				},'->',{
					text: '保存',
					itemId: 'saveNews', 
					iconCls: 'hkyg-save'
				}]	
			}]
		},{
			xtype: 'panel',
			title: '用户管理',
			layout: 'hbox',
			hidden: current_user_authority!=1,
			iconCls: 'hkyg-user',
			listeners:{
				
			},
			items:[{
				xtype: 'grid',
				itemId: 'userGrid',
				flex: 2,
				height: '100%',
				store: me.usersStore,
				tbar:[{
					text: '新增',
					iconCls: 'hkyg-user-add',
					menu: Ext.create('Ext.menu.Menu',{
								items:[{
									text: '普通用户',
									iconCls: 'hkyg-news-add',
									handler: function(btn){
										btn.up('newsPanel').addUser(0);
									}
								},{
									text: '管理员',
									iconCls: 'hkyg-news-add',
									handler: function(btn){
										btn.up('newsPanel').addUser(1);
									}
								}]
						  }),
					listeners:{
						mouseover: function(btn, e){
							btn.showMenu();
						}
					}
				},{
					text: '修改',
					iconCls: 'hkyg-user-edt',
					handler: function(btn){
						btn.up('newsPanel').modifyUser();
					}
				},{
					text: '删除',
					iconCls: 'hkyg-user-del',
					itemId: 'delUsers',
					handler: function(btn){
						btn.up('newsPanel').delUser();
					}
				},{
					text: '刷新',
					iconCls: 'hkyg-refresh',
					itemId: 'refresh',
					handler: function(btn){
						btn.up('newsPanel').refreshUserList();
					}
//				},'-',{
//					xtype: 'textfield',
//					itemId: 'searchTitle',
//					emptyText: '用户名、真实姓名',
//					enableKeyEvents: true,
//		 	 		listeners: {
//			 	 		keypress: function(scope, e) {
//							if(e.keyCode == e.ENTER || e.keyCode == 10) {
//								me.searchUser();
//							}
//			 	 		}
//		 	 		}
//				},{
//					text: '搜索',
//					itemId: 'searchBtn',
//					iconCls: 'hkyg-search'
				}],
				dockedItems:[{
		            xtype: 'pagingtoolbar',
		            store: me.usersStore,
		            dock: 'bottom',
		            displayInfo: true
		        }],
				features:[
					Ext.create('Ext.grid.feature.Grouping',{
						groupHeaderTpl: '{name} ({rows.length} 行)'
					})
				],
				columnLines: true,
				columns:[{
					text: '用户类型',
					dataIndex: 'authority',
					width: 70,
					renderer: function(value){
						switch(value){
							case 0:
								return '普通用户';
								break;
							case 1:
								return '管理员';
								break;
							default:
								break;
						}
					}
				},{
					text: '用户名',
					dataIndex: 'user_name',
					flex: 1
				},{
					text: '真实姓名',
					dataIndex: 'real_name',
					flex: 1
				},{
					text: '性别',
					dataIndex: 'gender',
					width: 40,
					renderer: function(value){
						switch(value){
							case 0:
								return '男';
								break;
							case 1:
								return '女';
								break;
							default:
								break;
						}
					}
				},{
					xtype: 'datecolumn',
					text: '最近登录时间',
					dataIndex: 'last_login_time',
					format: 'y-m-d H:i:s',
					width: 150
				},{
					text: '创建者',
					dataIndex: 'create_user',
					width: 90
				},{
					xtype: 'datecolumn',
					text: '创建时间',
					dataIndex: 'create_time',
					format: 'y-m-d H:i:s',
					width: 150
				},{
					text: '最近修改人',
					dataIndex: 'modify_user',
					width: 90
				},{
					xtype: 'datecolumn',
					text: '最近更新时间',
					dataIndex: 'modify_time',
					format: 'y-m-d H:i:s',
					width: 150
				}]
			}]
		},{
			xtype: 'form',
			itemId: 'chPsdFrm',
			title: '密码修改',
			iconCls: 'hkyg-password',
			url: 'hkyg/Background.do?method=changePassword',
			defaults: {
				margin: '5 5 5 5',
				xtype: 'textfield',
				inputType: 'password',
				allowBlank: false,
				msgTarget: 'under'
			},
			items: [
			        {
			        	hidden: true,
			        	name: 'user_name',
			        	value: current_user_name
			        },
			        {
			        	fieldLabel: '当前密码',
			        	name: 'password'
			        },
			        {
			        	fieldLabel: '新密码',
			        	name: 'new_password',
			        	id: 'pass1'
			        },
			        {
			        	fieldLabel: '密码确认',
			        	name: 'new_password2',
			        	fieldLabel: '重复密码',  
                        vtype: 'repetition',  //指定repetition验证类型  
                        repetition: { targetCmpId: 'pass1' }  //配置repetition验证，提供目标组件（表单）ID  
			        },
			        {
			        	xtype: 'button',
						text: '修改',
						iconCls: 'hkyg-save',
						handler: function() {
							var form = me.down('form[itemId=chPsdFrm]');
							if (form.getForm().isValid()) {
					              form.submit({
					                  success: function(form, action) {
					                  	Ext.Msg.alert('提示', '修改成功');
					                  },
					                  failure: function(form, action) {
					                      Ext.Msg.alert('提示', '修改失败');
					                  }
					              });
				            } 
						}
					}]
				}
			],
		me.callParent(arguments);
	},
	doSearch: function() {
		var me = this;
    	var searchTitle = me.down('textfield[itemId=searchTitle]');
    	Ext.apply(me.newsStore.proxy.extraParams,{query: searchTitle.getValue()});
    	me.newsStore.loadPage(1);
	},
	cleanEdtPanel: function() {
		var me = this;
		var titleFld = me.down('textfield[itemId=title]');
    	var contentFld = me.down('htmleditor');
    	titleFld.reset();
    	contentFld.reset();
	},
    addUser: function(authority){
    	var newsPanel = this;
    	var usersStore = newsPanel.usersStore;
    	var user_rec = Ext.create('hkyg.model.UserInfo');
    	user_rec.set('authority', authority);
    	var EdtUserInfo = Ext.widget('edt_UserInfo',{
    							record: user_rec,
    							gridStore: usersStore,
    							isAddNew: true
    					  });
    	EdtUserInfo.show();
    },
    modifyUser: function(){
    	var newsPanel = this;
    	var usersStore = newsPanel.usersStore;
    	var selModel = newsPanel.down('gridpanel[itemId=userGrid]').getSelectionModel();
		if(!selModel.hasSelection()){
			Ext.Msg.alert('提示','请先选择需要修改的用户！');
			return;
		}
		var user_rec = selModel.getSelection()[0];
    	var EdtUserInfo = Ext.widget('edt_UserInfo',{
    							record: user_rec,
    							gridStore: usersStore,
    							isAddNew: false
    					  });
    	EdtUserInfo.show();
    },
    delUser: function(){
    	var newsPanel = this;
    	var selModel = newsPanel.down('gridpanel[itemId=userGrid]').getSelectionModel();
		if(!selModel.hasSelection()){
			Ext.Msg.alert('提示','请先选择需要删除的用户！');
			return;
		}
		var user_rec = selModel.getSelection()[0];
		var who = null;
		if(user_rec.get('authority') == 0){
			who = '普通用户';
		}else if(user_rec.get('authority') == 1){
			who = '<font color="red">管理员</font>';
		}
		Ext.Msg.confirm('提示','你确定要删除'+who+'[ '+user_rec.get('user_name')+' ]吗?',
	     	function fn(id){
				if(id==Ext.Msg.buttonIds[1]){
					Ext.Ajax.request({
						url: 'hkyg/Background.do?method=delUser',
						params: user_rec.getData(),
						success: function(response){
							newsPanel.usersStore.load();
						}
					});
				}
		});
    },
    refreshUserList: function(){
    	var newsPanel = this;
    	newsPanel.usersStore.load();
    },
    searchUser: function(){
    	
    }
});